package com.qrxl.config;

import com.qrxl.common.JGConstant;
import com.qrxl.common.exception.CustomException;
import com.qrxl.enums.EnumSysFlag;
import com.qrxl.enums.EnumUserType;
import com.qrxl.enums.HjReturnCode;
import com.qrxl.user.vo.UserLoginInfo;
import com.qrxl.util.JGAssert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {
    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //默认打开文档首页
        if (request.getRequestURI().equalsIgnoreCase("/")) {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter printWriter = null;
            try {
                printWriter = response.getWriter();
                printWriter.print("<script type='text/javascript'>parent.location.href='doc.html';</script>");
            } catch (IOException e) {
                log.error("", e);
            } finally {
                printWriter.flush();
                printWriter.close();
                return false;
            }
        }

        //统一拦截（查询当前session是否存在user）(这里user会在每次登陆成功后，写入session)
        UserLoginInfo ul = (UserLoginInfo) request.getSession().getAttribute(JGConstant.USER_SESSION_KEY);
        if (ul == null) {
            throw new CustomException(HjReturnCode.NO_LOGIN_ERROR, "请先登录");
        }
        if (!request.getMethod().equalsIgnoreCase(HttpMethod.GET.name())) {
            if (ul.getType().equals(EnumUserType.SUPPER_ADMIN.getCode())) {
                return true;
            }
            //非get方法需要写权限
            JGAssert.isTrue(ul.getRoleList().stream().allMatch(one -> one.getType().equals(EnumSysFlag.YES.getCode())), "只读用户，权限不足!");
        }
        return true;
    }


    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        System.out.println("执行了TestInterceptor的afterCompletion方法");
    }

}
